package cn.xianyang.org.service.impl;

import cn.xianyang.basic.service.impl.BaseServiceImpl;
import cn.xianyang.basic.util.MD5Utils;
import cn.xianyang.basic.util.StrUtils;
import cn.xianyang.org.domain.Employee;
import cn.xianyang.org.mapper.EmployeeMapper;
import cn.xianyang.org.service.IEmployeeService;
import cn.xianyang.user.domain.Logininfo;
import cn.xianyang.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
//只读 ,事务传播机制支持
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Override
    public void save(Employee employee) {
        initEmployee(employee);
        //要级联保存logininfo
        Logininfo logininfo = emp2Logininfo(employee);
        logininfoMapper.save(logininfo);
        employee.setLogininfo_id(logininfo.getId());
        employeeMapper.save(employee);
    }

    private Logininfo emp2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        //把employee同名拷贝给logininfo
        BeanUtils.copyProperties(employee,logininfo);
        //设置type  ，这是员工
        logininfo.setType(0);
        return logininfo;
    }

    private void initEmployee(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        //设置盐值加密
        String md5Pwd = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        //原密码
        employee.setSalt(salt);
        //加密之后比对的密码
        employee.setPassword(md5Pwd);
    }

    @Override
    public void update(Employee employee) {

        super.update(employee);
    }

    @Override
    public void removeById(Long id) {
        super.removeById(id);

    }

    @Override
    public Employee loadByLogininfoId(Long id) {
        return employeeMapper.loadByLogininfoId(id);
    }

    @Override
    public List<Employee> queryShopEmployees(Long shopId) {
        return employeeMapper.queryShopEmployees(shopId);
    }
}
